<template>
	<view class="order-container">
		<!-- 顶部搜索栏 -->
		<view class="header">
			<view class="header-content">
				<view class="search-container">
					<view class="search-box">
						<image src="/static/image/icon_search.png" class="search-icon" mode="aspectFit"></image>
						<input type="text" placeholder="搜索订单号" v-model="searchKeyword" class="search-input"
							placeholder-class="search-placeholder" @input="onSearchInput" />
					</view>

          <view class="search-btn" @click="handleSearch">
            <text class="search-btn-text">搜索</text>
          </view>
				</view>
			</view>
		</view>

		<!-- 分类标签 -->
		<view class="category-tabs" :style="{ marginTop: (statusBarHeight + navBarHeight) + 'px' }">
			<view v-for="(category, index) in categories" :key="index" class="category-item"
				:class="[activeCategory === index ? 'active' : '']" @click="switchCategory(index)">
				<text class="category-text">{{ category.name }}</text>
			</view>
		</view>

		<!-- 订单列表 -->
		<scroll-view class="order-list" scroll-y="true"  @refresherrefresh="onRefresh"
			@scrolltolower="loadMore">
			<!-- 加载状态 -->
			<view v-if="loading" class="loading-state">
				<text class="loading-text">加载中...</text>
			</view>

			<!-- 空状态 -->
			<view v-else-if="filteredOrderList.length === 0" class="empty-state">
				<image src="/static/image/empty_order.png" class="empty-icon" mode="aspectFit"></image>
				<text class="empty-text">暂无订单</text>
				<text class="empty-desc">快去下单吧~</text>
			</view>

			<!-- 订单列表 -->
			<view v-else class="order-list-container">
				<view v-for="(order, index) in filteredOrderList" :key="order.id" class="order-item">
					<!-- 订单头部 -->
					<view class="order-header">
						<view class="order-number">
							<text class="order-number-text">订单号 {{ order.order_no }}</text>
							<text class="copy-btn" @click="copyOrderNumber(order.order_no)">复制</text>
						</view>
						<view class="order-status" :class="[getStatusClass(order.status)]">
							<text class="status-text">{{ getStatusText(order.status) }}</text>
						</view>
					</view>

					<!-- 订单信息 -->
					<view class="order-product" v-for="item in order.orderItems" @click="viewOrderDetail(order)">
						<image :src="item.product_cover" class="product-image" mode="aspectFill"></image>
						<view class="product-info">
							<text class="product-title">{{ item.product_name }}</text>
							<text class="product-desc">{{ getOrderDesc(item.sku_spec) }}</text>
							<text class="order-time">{{ formatTime(order.create_time) }}</text>
						</view>
						<view class="product-price">
							<text class="price-symbol">¥</text>
							<text class="price-value">{{ order.amount || '0.00' }}</text>
						</view>
					</view>

					<!-- 操作按钮 -->
					<view class="order-actions">
						<view v-if="order.status === 'pending_pricing'" class="action-btn primary"
							@click="contactPricing(order)">
							<text class="action-text">联系定价</text>
						</view>
						<view v-else-if="order.status === 'pending'" class="action-btn primary"
							@click="payOrder(order)">
							<text class="action-text">支付</text>
						</view>
						<view v-else-if="order.status === 'pending_receipt'" class="action-btn primary"
							@click="confirmReceipt(order)">
							<text class="action-text">确认收货</text>
						</view>
						<view v-else-if="order.status === 'shipped'" class="action-btn primary"
							@click="viewLogistics(order)">
							<text class="action-text">查看物流</text>
						</view>
						<view v-else-if="order.status === 'completed'" class="action-btn secondary"
							@click="writeReview(order)">
							<text class="action-text">评价</text>
						</view>
						<view v-else-if="order.status === 'refunding'" class="action-btn secondary"
							@click="viewRefund(order)">
							<text class="action-text">退款详情</text>
						</view>

						<!-- 通用操作按钮 -->
						<view class="action-btn secondary" @click="viewOrderDetail(order)">
							<text class="action-text">订单详情</text>
						</view>

						<view v-if="order.status === 'pending' || order.status === 'pending_pricing'"
							class="action-btn secondary" @click="cancelOrder(order)">
							<text class="action-text">取消订单</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 加载更多 -->
			<view v-if="hasMore" class="load-more" @click="loadMore">
				<text class="load-more-text">加载更多</text>
			</view>
			<view v-else class="no-more">
				<text class="no-more-text">没有更多了</text>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import {
		ORDER_STATUS_TEXT,
		ORDER_STATUS
	} from "../../utils/enum";

	export default {
		data() {
			return {
				statusBarHeight: 0,
				navBarHeight: 0,
				searchKeyword: '',
				activeCategory: 0,
				hasMore: true,
				loading: false,
				currentPage: 1,
				categories: [{
						name: '全部',
						status: ''
					},
					{
						name: '待支付',
						status: ORDER_STATUS.PENDING
					},
					{
						name: '待收货',
						status: ORDER_STATUS.PENDING_RECEIPT
					},
					{
						name: '退款中',
						status: ORDER_STATUS.REFUNDING
					},
					{
						name: '已完成',
						status: ORDER_STATUS.COMPLETED
					},
					{
						name: '已取消',
						status: ORDER_STATUS.CANCELLED
					}
				],
				orderList: []
			}
		},
		computed: {
			// 过滤后的订单列表
			filteredOrderList() {
				let filtered = this.orderList;

				// 根据分类过滤
				if (this.activeCategory > 0) {
					const currentStatus = this.categories[this.activeCategory].status;
					if (currentStatus) {
						filtered = filtered.filter(order => order.status === currentStatus);
					}
				}

				// 根据搜索关键词过滤
				if (this.searchKeyword.trim()) {
					const keyword = this.searchKeyword.toLowerCase();
					filtered = filtered.filter(order =>
						order.order_no.toLowerCase().includes(keyword) ||
						this.getOrderTitle(order).toLowerCase().includes(keyword) ||
						this.getOrderDesc(order).toLowerCase().includes(keyword)
					);
				}

				return filtered;
			}
		},
		methods: {
			// 获取系统信息
			getSystemInfo() {
				const systemInfo = uni.getSystemInfoSync();
				this.statusBarHeight = systemInfo.statusBarHeight;

				if (uni.getMenuButtonBoundingClientRect) {
					const menuButtonInfo = uni.getMenuButtonBoundingClientRect();
					this.navBarHeight = menuButtonInfo.height + (menuButtonInfo.top - this.statusBarHeight) * 2;
				} else {
					this.navBarHeight = 44;
				}
			},

			// 搜索输入
			onSearchInput(e) {
				this.searchKeyword = e.detail.value;
			},

			// 执行搜索
			handleSearch() {
				if (!this.searchKeyword.trim()) {
					uni.showToast({
						title: '请输入搜索关键词',
						icon: 'none'
					});
					return;
				}

				uni.showLoading({
					title: '搜索中...'
				});

				// 重置页码并搜索
				this.currentPage = 1;
				const params = {
					user_id: this.userInfo.id,
					pageNo: this.currentPage,
					pageSize: 10,
					keyword: this.searchKeyword.trim()
				};

				this.$api.getOrderList(params).then(res => {
					uni.hideLoading();
					if (res && res.list) {
						this.orderList = res.list;
						this.hasMore = this.orderList.length < res.total;
					}
				}).catch(error => {
					uni.hideLoading();
					console.error('搜索订单失败:', error);
					uni.showToast({
						title: '搜索失败',
						icon: 'none'
					});
				});
			},

			// 切换分类
			switchCategory(index) {
				this.activeCategory = index;

				uni.showLoading({
					title: '加载中...'
				});

				// 重置页码
				this.currentPage = 1;

				// 根据分类加载数据
				const currentStatus = this.categories[index].status;
				const params = {
					user_id: this.userInfo.id,
					pageNo: this.currentPage,
					pageSize: 10
				};

				// 如果有状态筛选，添加状态参数
				if (currentStatus) {
					params.status = currentStatus;
				}

				this.$api.getOrderList(params).then(res => {
					uni.hideLoading();
					if (res && res.list) {
						this.orderList = res.list;
						this.hasMore = this.orderList.length < res.total;
					}
				}).catch(error => {
					uni.hideLoading();
					console.error('获取订单列表失败:', error);
					uni.showToast({
						title: '获取订单列表失败',
						icon: 'none'
					});
				});
			},

			// 获取状态文本
			getStatusText(status) {
				const statusMap = {
					'pending_pricing': '待定价',
					'pending': '待付款',
					'paid': '已付款',
					'shipped': '已发货',
					'pending_receipt': '待收货',
					'completed': '已完成',
					'cancelled': '已取消',
					'refunding': '退款中',
					'refunded': '已退款'
				};
				return statusMap[status] || '未知状态';
			},

			// 获取状态样式类
			getStatusClass(status) {
				const classMap = {
					'pending_pricing': 'status-pending-pricing',
					'pending': 'status-pending',
					'paid': 'status-paid',
					'shipped': 'status-shipped',
					'pending_receipt': 'status-pending-receipt',
					'completed': 'status-completed',
					'cancelled': 'status-cancelled',
					'refunding': 'status-refunding',
					'refunded': 'status-refunded'
				};
				return classMap[status] || 'status-unknown';
			},

			// 复制订单号
			copyOrderNumber(orderNo) {
				uni.setClipboardData({
					data: orderNo,
					success: () => {
						uni.showToast({
							title: '订单号已复制',
							icon: 'success'
						});
					}
				});
			},

			// 联系定价
			contactPricing(order) {
				uni.showModal({
					title: '联系定价',
					content: '是否联系工坊进行定价？',
					success: (res) => {
						if (res.confirm) {
							// 解析订单参数获取工坊信息
							let storeId = order.store_id;
							let storeName = '工坊';

							if (order.order_params) {
								try {
									const params = JSON.parse(order.order_params);
									if (params.store_id) {
										storeId = params.store_id;
									}
									if (params.store_name) {
										storeName = params.store_name;
									}
								} catch (e) {
									console.error('解析订单参数失败:', e);
								}
							}

							// 跳转到客服聊天页面
							uni.navigateTo({
								url: `/pages/service/chat?id=${storeId}&name=${storeName}&order_id=${order.id}`
							});
						}
					}
				});
			},

			// 查看订单详情
			viewOrderDetail(order) {
				uni.navigateTo({
					url: `/pages/order/detail?id=${order.id}`
				});
			},

			// 支付订单
			payOrder(order) {
				uni.showModal({
					title: '确认支付',
					content: `确认支付订单 ${order.order_no}？金额：¥${order.amount || '0.00'}`,
					success: (res) => {
						if (res.confirm) {
							this.getPay(order.id)
						}
					}
				});
			},
			getPay(order_id) {
				uni.showLoading({
					title: '微信支付请求'
				});
				const that = this
				this.$api.createPay({
					order_id
				}).then(payment => {
					uni.requestPayment({
						provider: 'wxpay',
						timeStamp: payment.timestamp,
						nonceStr: payment.nonce_str,
						package: payment.package,
						signType: payment.signType,
						paySign: payment.paySign,
						success: (result) => {
							uni.showToast({
								title: '支付成功'
							});

							// 刷新订单状态
							that.refreshOrderStatus(order_id, 'paid');
						},
						fail: (result) => {
							uni.showToast({
								icon: 'none',
								title: '支付失败',
							});
						},
						complete: () => {

						}
					});
				})
			},
			// 确认收货
			confirmReceipt(order) {
				uni.showModal({
					title: '确认收货',
					content: '确认已收到商品？',
					success: (res) => {
						if (res.confirm) {
							uni.showLoading({
								title: '确认中...'
							});

							// TODO: 调用确认收货接口
							setTimeout(() => {
								uni.hideLoading();
								uni.showToast({
									title: '确认收货成功',
									icon: 'success'
								});
								// 刷新订单状态
								this.refreshOrderStatus(order.id, 'completed');
							}, 1000);
						}
					}
				});
			},

			// 查看物流
			viewLogistics(order) {
				uni.navigateTo({
					url: `/pages/order/logistics?id=${order.id}`
				});
			},

			// 写评价
			writeReview(order) {
				uni.navigateTo({
					url: `/pages/order/comment?id=${order.id}`
				});
			},

			// 查看退款详情
			viewRefund(order) {
				uni.navigateTo({
					url: `/pages/order/refund?id=${order.id}`
				});
			},

			// 取消订单
			cancelOrder(order) {
				uni.showModal({
					title: '取消订单',
					content: '确认取消该订单？',
					success: (res) => {
						if (res.confirm) {
							uni.showLoading({
								title: '取消中...'
							});

							// 调用取消订单接口
							const cancelData = {
								id: order.id,
								user_id: this.userInfo.id
							};

							this.$api.cancelOrder(cancelData).then(res => {
								uni.hideLoading();
								uni.showToast({
									title: '订单已取消',
									icon: 'success'
								});
								// 刷新订单状态
								this.refreshOrderStatus(order.id, 'cancelled');
							})
						}
					}
				});
			},

			// 刷新订单状态
			refreshOrderStatus(orderId, newStatus) {
				const orderIndex = this.orderList.findIndex(order => order.id === orderId);
				if (orderIndex !== -1) {
					this.orderList[orderIndex].status = newStatus;
				}
			},

			// 下拉刷新
			onRefresh() {
				uni.showLoading({
					title: '刷新中...'
				});

				// 重新加载订单列表
				this.loadOrderList();
			},

			// 加载更多
			loadMore() {
				if (!this.hasMore || this.loading) return;

				this.loading = true;
				uni.showLoading({
					title: '加载中...'
				});

				// 计算下一页
				this.currentPage += 1;
				const params = {
					user_id: this.userInfo.id,
					pageNo: this.currentPage,
					pageSize: 10
				};

				this.$api.getOrderList(params).then(res => {
					this.loading = false;
					uni.hideLoading();

					if (res && res.list && res.list.length > 0) {
						this.orderList = [...this.orderList, ...res.list];
						this.hasMore = this.orderList.length < res.total;
					} else {
						this.hasMore = false;
					}
				}).catch(error => {
					this.loading = false;
					uni.hideLoading();
					console.error('加载更多订单失败:', error);
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					});
				});
			},

			// 获取订单图片
			getOrderImage(order) {
				// 如果有模型文件，显示模型文件图标
				if (order.model_file) {
					return '/static/image/icon_upload_model.png';
				}
				// 默认显示工坊图标
				return '/static/image/icon_workshop.png';
			},

			// 获取订单标题
			getOrderTitle(order) {
				// 解析订单参数获取工坊信息
				if (order.order_params) {
					try {
						const params = JSON.parse(order.order_params);
						if (params.store_name) {
							return params.store_name;
						}
					} catch (e) {
						console.error('解析订单参数失败:', e);
					}
				}
				return '3D打印订单';
			},

			// 获取订单描述
			getOrderDesc(sku_spec) {
        let _sku_spec = JSON.parse(sku_spec)
        let desc = ''
        if (_sku_spec) {
          for (let key in _sku_spec) {
            desc += `${_sku_spec[key]} `
          }
        }
        return desc
			},

			// 格式化时间
			formatTime(timeStr) {
				if (!timeStr) return '';
				const date = new Date(timeStr);
				return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
			},

			// 初始化数据
			initData() {
				this.loading = true;
				uni.showLoading({
					title: '加载中...'
				});

				// 调用API获取订单列表
				this.loadOrderList();
			},

			// 加载订单列表
			loadOrderList() {
				// 重置页码
				this.currentPage = 1;

				const params = {
					user_id: this.userInfo.id,
					pageNo: this.currentPage,
					pageSize: 10
				};

				this.$api.getOrderList(params).then(res => {
					this.loading = false;
					uni.hideLoading();

					if (res && res.list) {
						this.orderList = res.list;
						this.hasMore = this.orderList.length < res.total;
					}
				}).catch(error => {
					this.loading = false;
					uni.hideLoading();
					console.error('获取订单列表失败:', error);
					uni.showToast({
						title: '获取订单列表失败',
						icon: 'none'
					});
				});
			}
		},
		onLoad() {
			this.initData();
			// this.getSystemInfo();
		}
	}
</script>

<style lang="scss">
	.order-container {
		height: 100vh;
		overflow: hidden;
		display: flex;
		flex-direction: column;
		background-color: #f5f5f5;
	}

	// 顶部搜索栏
	.header {
		//position: fixed;
		//top: 0;
		//left: 0;
		//right: 0;
		//z-index: 1000;
		background-color: #fff;
		//padding-right: 140rpx;

		.header-content {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 0 32rpx;
		}

		.search-container {
			flex: 1;
			display: flex;
			align-items: center;
			gap: 20rpx;
			margin-right: 20rpx;

			.search-box {
				flex: 1;
				display: flex;
				align-items: center;
				background-color: #f5f5f5;
				border-radius: 50rpx;
				padding: 0 24rpx;
				height: 72rpx;
				border: 2rpx solid #A6A6A6;
				position: relative;

				.search-icon {
					width: 32rpx;
					height: 32rpx;
					margin-right: 16rpx;
				}

				.search-input {
					flex: 1;
					font-size: 28rpx;
					color: #333;
				}

				.search-placeholder {
					color: #999;
				}
			}

			.search-btn {
        color: #333;
				.search-btn-text {
					font-size: 28rpx;
				}

				&:active {
					background-color: #555;
				}
			}
		}
	}

	// 分类标签
	.category-tabs {
		display: flex;
		align-items: center;
		padding: 24rpx 32rpx;
		background-color: #fff;
		gap: 40rpx;
		border-bottom: 2rpx solid #f0f0f0;
		overflow-x: auto;

		.category-item {
			flex-shrink: 0;
			position: relative;
			padding-bottom: 16rpx;

			.category-text {
				font-size: 28rpx;
				color: #666;
				font-weight: 400;
			}

			&.active {
				.category-text {
					color: #333;
					font-weight: 500;
				}

				&::after {
					content: '';
					position: absolute;
					bottom: 0;
					left: 0;
					right: 0;
					height: 4rpx;
					background-color: #539DF3;
					border-radius: 2rpx;
				}
			}

			&:active {
				opacity: 0.7;
			}
		}
	}

	// 订单列表
	.order-list {
		flex-grow: 1;
		padding-top: 24rpx;
		width: 100%;
		box-sizing: border-box;
	}

	// 加载状态
	.loading-state {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 120rpx 32rpx;

		.loading-text {
			font-size: 28rpx;
			color: #999;
		}
	}

	// 空状态
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 120rpx 32rpx;

		.empty-icon {
			width: 200rpx;
			height: 200rpx;
			margin-bottom: 32rpx;
			opacity: 0.6;
		}

		.empty-text {
			font-size: 32rpx;
			color: #999;
			margin-bottom: 16rpx;
		}

		.empty-desc {
			font-size: 26rpx;
			color: #ccc;
		}
	}

	.order-list-container {
		padding: 0 32rpx;
	}

	.order-item {
		background-color: #fff;
		border-radius: 16rpx;
		margin-bottom: 24rpx;
		overflow: hidden;
	}

	// 订单头部
	.order-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 24rpx 32rpx;
		border-bottom: 1rpx solid #f0f0f0;

		.order-number {
			display: flex;
			align-items: center;
			gap: 12rpx;

			.order-number-text {
				font-size: 28rpx;
				color: #333;
				font-weight: 500;
			}

			.copy-btn {
				font-size: 24rpx;
				color: #539DF3;
				padding: 4rpx 8rpx;
				border-radius: 4rpx;
				background-color: rgba(255, 107, 53, 0.1);

				&:active {
					background-color: rgba(255, 107, 53, 0.2);
				}
			}
		}

		.order-status {
			padding: 8rpx 16rpx;
			border-radius: 8rpx;
			font-size: 24rpx;

			&.status-pending-pricing {
				background-color: #e3f2fd;
				color: #2196f3;
			}

			&.status-pending {
				background-color: #fff3e0;
				color: #539DF3;
			}

			&.status-paid {
				background-color: #e3f2fd;
				color: #2196f3;
			}

			&.status-shipped {
				background-color: #e8f5e8;
				color: #4caf50;
			}

			&.status-pending-receipt {
				background-color: #fff8e1;
				color: #ff9800;
			}

			&.status-completed {
				background-color: #e8f5e8;
				color: #4caf50;
			}

			&.status-cancelled {
				background-color: #f5f5f5;
				color: #999;
			}

			&.status-refunding {
				background-color: #ffebee;
				color: #f44336;
			}

			&.status-refunded {
				background-color: #f5f5f5;
				color: #999;
			}

			.status-text {
				font-weight: 500;
			}
		}
	}

	// 商品信息
	.order-product {
		display: flex;
		align-items: center;
		padding: 24rpx 32rpx;
		gap: 20rpx;

		.product-image {
			width: 120rpx;
			height: 120rpx;
			border-radius: 50%;
			flex-shrink: 0;
		}

		.product-info {
			flex: 1;
			display: flex;
			flex-direction: column;
			gap: 8rpx;

			.product-title {
				font-size: 28rpx;
				color: #333;
				font-weight: 500;
				line-height: 1.4;
			}

			.product-desc {
				font-size: 24rpx;
				color: #666;
			}

			.order-time {
				font-size: 22rpx;
				color: #999;
				margin-top: 4rpx;
			}
		}

		.product-price {
			display: flex;
			align-items: baseline;
			gap: 4rpx;

			.price-symbol {
				font-size: 24rpx;
				color: #333;
			}

			.price-value {
				font-size: 32rpx;
				color: #333;
				font-weight: 600;
			}
		}
	}

	// 操作按钮
	.order-actions {
		display: flex;
		justify-content: flex-end;
		align-items: center;
		gap: 16rpx;
		padding: 24rpx 32rpx;
		border-top: 1rpx solid #f0f0f0;

		.action-btn {
			padding: 12rpx 24rpx;
			border-radius: 8rpx;
			font-size: 24rpx;
			font-weight: 500;

			&.primary {
				background-color: #539DF3;
				color: #fff;

				&:active {
					background-color: #e55a2b;
				}
			}

			&.secondary {
				background-color: #f5f5f5;
				color: #666;

				&:active {
					background-color: #e8e8e8;
				}
			}

			.action-text {
				font-size: 26rpx;
			}
		}
	}

	// 加载更多
	.load-more {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 80rpx;
		margin: 40rpx 0;

		.load-more-text {
			font-size: 28rpx;
			color: #666;
		}

		&:active {
			opacity: 0.7;
		}
	}

	.no-more {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 80rpx;
		margin: 40rpx 0;

		.no-more-text {
			font-size: 24rpx;
			color: #ccc;
		}
	}
</style>
